from django.test import TestCase
1111111111111
# 自定义类视图的测试
class View:
    http_method_names = ['get', 'post', 'put', 'patch','delete','''head', 'options', 'trace']
        
    @classmethod
    # 这是一个工厂函数
    def as_view(cls,**initkwargs):
        # 模拟django的as_view方法,返回一个视图函数
        # 参数检查
        for key in initkwargs:
            if key in cls.http_method_names:
                raise TypeError(f"不能使用Http方法名{key}作为视图函数的参数名")

        # 返回视图函数
        def view(request,*args,**kwargs):
            # 创建一个类视图的实例
            self = cls(**initkwargs)
            # 初始化请求属性,模拟setup
            self.request = request
            self.args = args
            self.kwargs = kwargs
            
            # 调用dispatch方法,模拟dispatch
            if request.method.lower() in self.http_method_names:
                # getattr(object,name,Default) 获取对象的属性值,如果没有属性,返回默认值
                handler = getattr(self,request.method.lower(),None)
                if handler:
                    return handler(request,*args,**kwargs)
        return view                

# 写一个实用的实例
class MyView(View):
    see = "hello"
    def __init__(self,**initkwargs):
        for key,value in initkwargs.items():
            setattr(self,key,value)
    def post(self,request,*args,**kwargs):
        return f"{self.see}"Post请求"

    def get(self,request,*args,**kwargs):
        return f"{self.see}"get请求"

# 模拟路由
urlpatterns = {
'/test/':MyView.as_view(see="你好")}

# 模拟请求
def handle_requet(path):
    view = urlpatterns.get(path)
    if view:
        class Request:
            method = method.upper()
        return view(Request(method))
    return "404 Not Found"

print(handle_requet('/test/')) # 你好get请求
print(handle_requet('/test/')) # 你好post请求
            